import { useState, useEffect } from "react";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import DataPaper from "./DataPaper";
import ToggleButtonGroup from "@mui/material/ToggleButtonGroup";
import ToggleButton from "@mui/material/ToggleButton";
import ButtonGroup from "@mui/material/ButtonGroup";
import storApis from "../apis/stors.mjs";
import { GM_registerMenuCommand } from "tm";
import { useThrottle } from "@react-hook/throttle";
import { titleFont, firstDlg, secondDlg, buttonFont } from "../data.mts";

export default function StorageDialog(properties: { inner?: HTMLElement }) {
  const [open, setOpen] = useState(false);
  const [openEd, setOpenEd] = useState(false);
  const [data, setData] = useState<Record<string, string>>({});
  const [sdata, setSData] = useState<Record<string, string>>({});
  const [content, setContent] = useThrottle("");
  const [edKey, setEdKey] = useThrottle("");
  const [edAdd, setEdAdd] = useState<boolean>(false);
  const [edType, setEdType] = useState<"local" | "session">("local");

  useEffect(() => {
    GM_registerMenuCommand("Storage UI", () => {
      setOpen(true);
      updateData();
    });
  }, []);

  const handleCloseEd = () => {
    setEdKey("");
    setContent("");
    setOpenEd(false);
  };

  const updateData = () => {
    storApis
      .query(globalThis.localStorage)
      .then((result) => {
        setData(result.data);
      })
      .catch(() => {
        setOpen(false);
      });
    storApis
      .query(globalThis.sessionStorage)
      .then((result) => {
        setSData(result.data);
      })
      .catch(() => {
        setOpen(false);
      });
  };

  return (
    <>
      <Dialog
        open={open}
        onClose={() => {
          setOpen(false);
        }}
        sx={firstDlg}
        container={properties.inner}
      >
        <DialogTitle sx={titleFont}>Storage</DialogTitle>
        <DialogContent
          sx={{
            display: "flex",
            flexDirection: "column",
          }}
        >
          <List
            sx={{
              width: "100%",
              maxWidth: 360,
              bgcolor: "background.paper",
              position: "relative",
              overflow: "auto",
              maxHeight: "60vh",
            }}
          >
            {Object.keys(data).map((key, index, keys) => (
              <ListItem key={"l" + key}>
                <DataPaper
                  text={`localStorage
${String(index + 1)}/${String(keys.length)}
${key}`}
                  dKey={key}
                  dValue={data[key]}
                  openEdit={() => {
                    setEdType("local");
                    setContent(data[key]);
                    setEdKey(key);
                    setEdAdd(false);
                    setOpenEd(true);
                  }}
                  remove={() => {
                    void storApis.change(globalThis.localStorage, key);
                    updateData();
                  }}
                />
              </ListItem>
            ))}
            {Object.keys(sdata).map((key, index, keys) => (
              <ListItem key={"s" + key}>
                <DataPaper
                  text={`sessionStorage
${String(index + 1)}/${String(keys.length)} ${key}`}
                  dKey={key}
                  dValue={sdata[key]}
                  openEdit={() => {
                    setEdType("session");
                    setContent(sdata[key]);
                    setEdKey(key);
                    setEdAdd(false);
                    setOpenEd(true);
                  }}
                  remove={() => {
                    void storApis.change(globalThis.sessionStorage, key);
                    updateData();
                  }}
                />
              </ListItem>
            ))}
          </List>
          <ButtonGroup fullWidth sx={{ mt: "5px" }}>
            <Button
              onClick={() => {
                setEdType("local");
                setEdKey("");
                setContent("");
                setEdAdd(true);
                setOpenEd(true);
              }}
              color="success"
              sx={{ fontSize: 16 }}
              variant="outlined"
            >
              添加
            </Button>
            {Object.keys(data).length > 0 || Object.keys(sdata).length > 0 ? (
              <Button
                color="error"
                sx={{ fontSize: 16 }}
                variant="outlined"
                // eslint-disable-next-line @typescript-eslint/no-misused-promises
                onClick={async () => {
                  await storApis.clear(globalThis.localStorage);
                  await storApis.clear(globalThis.sessionStorage);
                  updateData();
                }}
              >
                清空
              </Button>
            ) : (
              void 0
            )}
          </ButtonGroup>
        </DialogContent>
      </Dialog>
      <Dialog
        open={openEd}
        onClose={handleCloseEd}
        container={properties.inner}
        sx={secondDlg}
      >
        <DialogTitle sx={titleFont}>{edAdd ? "添加" : "编辑"}</DialogTitle>
        <DialogContent
          sx={{
            display: "flex",
            flexDirection: "column",
          }}
        >
          <ToggleButtonGroup
            color="primary"
            value={edType}
            disabled={!edAdd}
            orientation="vertical"
            exclusive
            fullWidth
            onChange={(_event, v) => {
              if (v !== null) {
                setEdType(v as "local" | "session");
              }
            }}
            sx={{
              my: "2px",
              mx: 0,
            }}
          >
            <ToggleButton
              value="local"
              sx={{
                fontSize: 15,
              }}
            >
              local Storage
            </ToggleButton>
            <ToggleButton
              value="session"
              sx={{
                fontSize: 15,
              }}
            >
              session Storage
            </ToggleButton>
          </ToggleButtonGroup>
          <TextField
            margin="dense"
            label="键"
            value={edKey}
            InputLabelProps={{ shrink: edKey !== "" }}
            error={edKey === ""}
            variant="standard"
            fullWidth
            required
            disabled={!edAdd}
            onChange={(v) => {
              setEdKey(v.target.value);
            }}
          />
          <TextField
            margin="dense"
            multiline
            rows={4}
            label="值"
            type="text"
            fullWidth
            InputLabelProps={{ shrink: content !== "" }}
            variant="standard"
            value={content}
            onChange={(v) => {
              setContent(v.target.value);
            }}
          />
        </DialogContent>
        <DialogActions>
          <Button sx={buttonFont} onClick={handleCloseEd}>
            取消
          </Button>
          <Button
            onClick={() => {
              if (edKey !== "") {
                void storApis.change(
                  edType === "local"
                    ? globalThis.localStorage
                    : globalThis.sessionStorage,
                  edKey,
                  content,
                );
                updateData();
                setOpenEd(false);
              }
            }}
            variant="contained"
            sx={buttonFont}
          >
            保存
          </Button>
        </DialogActions>
      </Dialog>
    </>
  );
}
